<template>
	<view class="audio-view">
		<h2 class="audio-name">{{ this.form.audioName }}</h2>
		<div class="play-btns">
			<view class="start">
				<u-icon v-if="status > 0" @click="reload" name="reload" color="#fcbd71" size="64"></u-icon>
			</view>
			<view class="center">
				<u-icon v-if="status === 0 || status === 2" @click="toggle" name="play-circle-fill" color="#2979ff" size="96"></u-icon>
				<u-icon v-else-if="status === 1" @click="toggle" name="pause-circle-fill" color="#2979ff" size="96"></u-icon>
			</view>
			<view class="end">
				<u-icon v-if="status > 0" @click="stop" name="minus-square-fill" color="#fa3534" size="64"></u-icon>
			</view>
		</div>
		<u-form :model="form" ref="uForm" label-width="80px" class="form">
			<u-form-item :label="'语速(' + getRate() + ')'">
				<view class="content-wrap">
					<view class="flex-full">
						<u-slider v-model="form.playbackRate" @end="handleChangeRate" step="2.5" min="25" max="100"></u-slider>
					</view>
				</view>
			</u-form-item>
			<u-form-item label="循环播放">
				<view class="content-wrap">
					<view class="flex-full">
						<u-switch v-model="form.loop" @change="handleChangeLoop"></u-switch>
					</view>
				</view>
			</u-form-item>
		</u-form>
	</view>
</template>

<script>
import audioSer from '@/api/service/audio.js'
	
export default {
	data() {
		return {
			status: 0,
			form: {
				id: null,
				audioName: '',
				filePath: '',
				playbackRate: 50,
				loop: false
			}
		}
	},

	onNavigationBarButtonTap (item) {
		// 删除
		if (item.index === 0) {
			this.handleDelete()
		}
		// 编辑
		else {
			this.handleEdit()
		}
	},

	onLoad(params) {
		this.params = params
		uni.$on('onRefreshAudioState', (data) => {
			console.log(666666)
			console.log(data)
			this.form.audioName = data.audioName
			this.form.filePath = data.filePath
      this.init()
		})
	},

	onUnload() {
		uni.$off('onRefreshAudioState')
	},

	mounted() {
		let params = this.params || {}
		if (!params.id) {
			return true
		}
		this.form.id = params.id
		audioSer.queryList(params).then(data => {
			data = data || []
			if (data.length) {
				this.form.filePath = data[0].filePath
				this.form.audioName = data[0].audioName
				this.init()
			}
		}).catch(e => {
			console.log(e)
		})
	},
	
	beforeDestroy(){
		this.destroy()
	},

	methods: {
    // 初始化资源
    init () {
      this.destroy()
      const innerAudioContext = uni.createInnerAudioContext();
      // innerAudioContext.autoplay = true;
      innerAudioContext.src = this.form.filePath
			innerAudioContext.playbackRate = this.getRate()
			innerAudioContext.loop = this.form.loop
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
      innerAudioContext.onError((res) => {
        console.log(res.errMsg)
        console.log(res.errCode)
      })
			innerAudioContext.onStop(() => {
        this.status = 0
      })
			innerAudioContext.onEnded(() => {
        this.status = 0
      })
			this.audioContext = innerAudioContext
    },
		getRate () {
			return this.form.playbackRate / 50
		},
		toggle () {
      if (!this.audioContext) {
				return true
			}
			if (this.status === 0 || this.status === 2) {
				this.audioContext.play()
				this.status = 1
			} else {
				this.audioContext.pause()
				this.status = 2
			}
		},
		reload () {
			this.stop()
			this.init()
			this.toggle()
		},
		stop () {
			if (this.audioContext) {
				this.audioContext.stop()
			}
			this.status = 0
		},
		destroy () {
			this.status = 0
			if (this.audioContext) {
			  try {
			    this.audioContext.pause();
			    this.audioContext.destroy()
			    this.audioContext = null
			  } catch (e) {
			    //TODO handle the exception
			  }
			}
		},
		handleChangeRate () {
			let val = this.getRate()
			if (val > 1.5) {
				val = val - 1.5 > (2 - 1.5) / 2 ? 2 : 1.5
			} else if (val > 1.25) {
				val = val - 1.25 > (1.5 - 1.25) / 2 ? 1.5 : 1.25
			} else if (val > 1) {
				val = val - 1 > (1.25 - 1) / 2 ? 1.25 : 1
			} else if (val > 0.8) {
				val = val - 0.8 > (1 - 0.8) / 2 ? 1 : 0.8
			} else if (val > 0.5) {
				val = val - 0.5 > (0.8 - 0.5) / 2 ? 0.8 : 0.5
			}
			this.form.playbackRate = val * 50
			if (this.audioContext) {
				this.audioContext.playbackRate = this.getRate()
			}
		},
		handleChangeLoop () {
			if (this.audioContext) {
				this.audioContext.loop = this.form.loop
			}
		},
		handleEdit () {
			if (!this.form.id) {
				this.$u.toast('无语音数据')
				return true
			}
			this.$tab.navigateTo('/pages/audio/edit?id=' + this.form.id)
		},
		handleDelete () {
			if (!this.form.id) {
				this.$u.toast('无语音数据')
				return true
			}
			uni.showModal({
				title: '提示',
				content: '确认删除该条记录吗？',
				success: (res) => {
					if (res.confirm) {
						let defer = audioSer.delete({ id: this.form.id })
						defer.then(() => {
							this.$u.toast('操作成功')
							uni.navigateBack({
								url: '/pages/audio/index'
							})
						}).catch(() => {
							this.$u.toast('操作失败')
						})
					}
				}
			})
		}
	}
}
</script>

<style lang="less">
	.audio-name {
		padding: 16px;
		text-align: center;
		color: #333;
		word-wrap: break-word;
	}
	.play-btns {
		padding: 16px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.form {
		padding: 16px;
	}
	.content-wrap {
		flex: 1;
		display: flex;
		align-items: center;
	}
	.flex-full {
		flex: 1;
	}
</style>
